<template>
  <el-form 
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    ref="RuleformRef"
    :disabled="true"
    >
    <el-row :gutter='20' style="position: relative;">
      <el-col v-for="formItem in formColum" :key="formItem.field" :span="formItem.colProps?.span?formItem.colProps?.span:12">
          <el-form-item
          :label="formItem.label" 
          :prop="formItem.field"
          >
          <template #default>
            <el-row v-if="formItem.field === 'templateName'" style="width: 100%;">
              <el-col>
                <el-select v-model="ruleForm['templateName']"  placeholder="请选择" style="width: 100%">
                  <el-option-group
                    v-for="group in resultTypeOpt"
                    :key="group.label"
                    :label="group.label"
                  >
                    <el-option
                      v-for="item in group.options"
                      :key="item.id"
                      :label="item.templateName"
                      :value="item.id"
                    />
                  </el-option-group>
                    
                </el-select>
                  
              </el-col>
              
            </el-row>
            <el-row v-else-if="formItem.field === 'earthquakeType'">
              <el-checkbox-group v-model="ruleForm['earthquakeType']">
                <el-checkbox  
                    v-for="dict in earthquakeTypeOpt"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.label"
                     />
              </el-checkbox-group>
            </el-row>
            <el-row v-else-if="formItem.field === 'expansionDistance'" style="width: 100%;">
              <el-col :span="20" class="el-colC">
                <el-input  v-model="ruleForm['expansionDistance']"
                :formatter="(value) => `${value}`.replace(/\D/g,'')"
                :parser="(value) => value.replace(/\D/g,'')"
                ></el-input>
              </el-col>
                <el-col :span="4" >
                千米
              </el-col>
            </el-row>
            <el-row v-else-if="formItem.field === 'rangeType'">
              <el-col :span="24">
                <el-radio-group v-model="ruleForm['rangeType']">
                  <el-radio key="0" :value="'0'" @click="clickClose">上传区域文件</el-radio>
                  <el-radio key="1" :value="'1'" @click="clickRadio" >按行政区域选择</el-radio>
                </el-radio-group>
              </el-col>
              <el-col :span="24" v-if="ruleForm['rangeType']==0">
                <UploadFileTo  v-model="ruleForm['list']"  @uploadSuccess="uploadSuccess" />
              </el-col>
              <el-col :span="24">
                <div class="mapCard">
                   <LoadMap :fileidInfo="fileidInfo" style="height: 100%" />
                </div>
              </el-col>
            </el-row>
            <el-row v-else-if="formItem.field === 'rangeRule'" style="width: 100%;">
              <FormTitle :title="'空间范围规则'" :pcontent="''" />
              <el-col>
                <el-radio-group v-model="ruleForm['rangeRule']" @change="clickLayer(ruleForm,ruleForm['rangeRule'])">
                  <el-radio key="1" :value="'0'"  >震中扩展范围</el-radio>
                  <el-radio key="2" :value="'1'"  >指定图层扩展</el-radio>
                </el-radio-group>
              </el-col>
              <el-row v-if="ruleForm['rangeRule'] === '0'" style="width: 100%;">
                <el-form-item label="震级" prop="magnitude">
                  <el-input v-model="ruleForm['magnitude']" 
                    @input="(value) => value.replace(/[^0-9.]/g, '').replace(/^(\d+\.\d{0,1}).*$/, '$1')"
                    placeholder="请输入" />
                </el-form-item>
                <el-form-item label="扩展范围" prop="extendedRange">
                  <el-col :span="18">
                    <el-input  v-model="ruleForm['extendedRange']"
                    :formatter="(value) => `${value}`.replace(/\D/g,'')"
                    :parser="(value) => value.replace(/\D/g,'')"
                    ></el-input>
                  </el-col>
                  <el-col :span="6">
                    千米
                  </el-col>
                </el-form-item>
                <el-form-item label="间隔距离" prop="intervalDistance">
                  <el-col :span="18">
                  <el-input  v-model="ruleForm['intervalDistance']"
                  :formatter="(value) => `${value}`.replace(/\D/g,'')"
                  :parser="(value) => value.replace(/\D/g,'')"
                  ></el-input>
                </el-col>
                <el-col :span="6">
                  千米
                </el-col>
                </el-form-item>
                <el-col :span="24">
                  示例：震级≤5.0，震中上下各扩100Km；震级＞5.0，震中上下再扩100Km基础上每增加0.1震级，上下各增加10Km。
                </el-col>
              </el-row>
              <el-row v-if="ruleForm['rangeRule'] === '1'" style="width: 100%;">
                <el-col :span="12">
                  <el-form-item label="图层选择" prop="layerType">
                    <el-select v-model="ruleForm['layerType']"  placeholder="请选择">
                        <el-option 
                            v-for="dict in layerTypeOpt"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                      </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="扩展范围" prop="extendedRange">
                  <el-col :span="18">
                    <el-input  v-model="ruleForm['extendedRange']"
                    :formatter="(value) => `${value}`.replace(/\D/g,'')"
                    :parser="(value) => value.replace(/\D/g,'')"
                    ></el-input>
                  </el-col>
                  <el-col :span="6">
                    千米
                  </el-col>
                </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="ruleForm['layerType'] === '1' && ruleForm['rangeRule'] === '1'" style="width: 100%;">
                <el-col :span="12">
                  <el-form-item label="烈度" prop="intensityType">
                    <el-select v-model="ruleForm['intensityType']"  placeholder="请选择">
                        <el-option 
                            v-for="dict in intensityTypeOpt"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                      </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="未达烈度扩展范围" prop="noExtendedRange">
                  <el-col :span="18">
                    <el-input  v-model="ruleForm['noExtendedRange']"
                    :formatter="(value) => `${value}`.replace(/\D/g,'')"
                    :parser="(value) => value.replace(/\D/g,'')"
                    ></el-input>
                  </el-col>
                  <el-col :span="6">
                    千米
                  </el-col>
                </el-form-item>
                </el-col>
              </el-row>
            </el-row>
            <el-row v-else-if="formItem.field === 'magnitude1'">
              <el-col :span="5">
                <el-input v-model="ruleForm[formItem.field]"
                :formatter="(value) =>value.replace(/[^0-9.]/g, '').replace(/^(\d+\.\d{0,1}).*$/, '$1')"
                :parser="(value) => value.replace(/[^0-9.]/g, '').replace(/^(\d+\.\d{0,1}).*$/, '$1')" 
                placeholder="请输入" />
              </el-col>
              
                <el-col :span="4" >
                    <el-select v-model="ruleForm['magnitude2']"  placeholder="请选择">
                        <el-option
                            v-for="dict in earthQuakeOpt"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                      </el-select>
                </el-col>
                <el-col :span="3" class="el-colC">
                  震级
                </el-col>
                <el-col :span="4" >
                    <el-select v-model="ruleForm['magnitude3']"  placeholder="请选择">
                        <el-option
                            v-for="dict in earthQuakeOpt1"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                      </el-select>
                </el-col>
                <el-col :span="5">
                <el-input v-model="ruleForm['magnitude4']"
                :formatter="(value) =>value.replace(/[^0-9.]/g, '').replace(/^(\d+\.\d{0,1}).*$/, '$1')"
                :parser="(value) => value.replace(/[^0-9.]/g, '').replace(/^(\d+\.\d{0,1}).*$/, '$1')" 
                placeholder="请输入" />
              </el-col>
            </el-row>
            <el-row v-else-if="formItem.field === 'intensity1'" style="width: 100%;">
              <el-col :span="6">
                <el-select v-model="ruleForm['intensity1']"  placeholder="请选择">
                        <el-option
                            v-for="dict in intensityOpt"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                      </el-select>
              </el-col>
                <el-col :span="4" >
                    <el-select v-model="ruleForm['intensity2']"  placeholder="请选择">
                        <el-option
                            v-for="dict in earthQuakeOpt"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                      </el-select>
                </el-col>
                <el-col :span="3" class="el-colC">
                  烈度
                </el-col>
                <el-col :span="4" >
                    <el-select v-model="ruleForm['intensity3']"  placeholder="请选择">
                        <el-option
                            v-for="dict in earthQuakeOpt1"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                      </el-select>
                </el-col>
                <el-col :span="6">
                  <el-select v-model="ruleForm['intensity4']"  placeholder="请选择">
                        <el-option
                            v-for="dict in intensityOpt"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                      </el-select>
                </el-col>
            </el-row>
            <el-input v-else v-model="ruleForm[formItem.field]"></el-input>
          </template>
        </el-form-item>
      </el-col>
      <ProvinceCity style="position: absolute;top: 190px; left: 260px" ref="provinceRef" :regionLists="ruleForm['regionList']"  @querySelect="querySelect"></ProvinceCity>
    </el-row>
  </el-form>

  <div style="text-align: center;">
    <el-button @click="setClose">关 闭</el-button>
  </div>
<!-- </Dialog> -->
</template>
<script lang="ts" setup>
import * as ftpApi from '@/api/productmange/imgProduce'
import { allSchemas, rules, formColum,earthquakeTypeOpt } from './filesRelease.data'
import UploadFileTo from '@/views/responseLevel/populationDensity/create/UploadFile.vue'
import ProvinceCity from '@/views/responseLevel/populationDensity/create/provinceCity.vue'
import { intensityTypeOpt,intensityOpt } from '../indexData';
import { label } from '@/api/adv';
import LoadMap from '@/views/earthquake/earthquakeServer/gis/LoadMap.vue'
defineOptions({ name: 'FilesReleaseForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const RuleformRef = ref() // 表单 Ref
const ruleForm = ref({
"ruleName": '', //"规则名称",
"templateName":'',// "模板名称", 
"templateId":'',// "模板ID", 
"magnitude1":'',// "震级范围", 
"magnitude2":'0',// "震级范围 符号", 
"magnitude3":'0',// "震级范围 符号", 
"magnitude4":'',// "震级范围", 
"intensity1":'',// "烈度范围", 
"intensity2":'0',// "烈度范围 符号", 
"intensity3":'0',// "烈度范围 符号", 
"intensity4":'',// "烈度范围", 
"earthquakeType":[],// "地震类型", 
list:[],
regionList:[],
"expansionDistance":'',// "区域外扩距离", 
"rangeRule":'0',// "空间范围规则（0：震中扩展范围、1：指定图层扩展）", 
"magnitude":'',// "震级", 
"extendedRange":'',// "扩展范围", 
"intervalDistance":'',// "间隔距离", 
"layerType":'',// "图层选择 1:影响场2：历史地震3：震中距", 
"intensityType":'',// "烈度", 
"noExtendedRange":'',// "未达烈度扩展范围" 
})
const earthQuakeOpt = ref([
{label:'≤',value:'0'},
{label:'<',value:'1'},
])
const earthQuakeOpt1 = ref([
{label:'≤',value:'0'},
{label:'<',value:'1'},
{label:'=',value:'2'},
])
const layerTypeOpt = ref( [
  {
    label: '影响场',
    value:'1'
  },
  {
    label: '历史地震',
    value:'2'
  },
  {
    label: '震中距',
    value:'3'
  }
])
const fileidInfo = ref({
  fileid: '',
  type: 0,
  xzqh:[],
  query: {
    tableName: '',
    fields: '',
    // owner:"private"
  }
})

/** 打开弹窗 */
const open = async (type: string, id?: number|string) => {
dialogVisible.value = true
dialogTitle.value = t('action.' + type)
formType.value = type
// 修改时，设置数据
if (id) {
  formLoading.value = true
  try {
    const data = await ftpApi.getByIdpictureRule({id:id})
    regionList.value=data.regionList
    data.earthquakeType= data.earthquakeType.split(',');
    ruleForm.value={...data}
  } finally {
    formLoading.value = false
  }
}else{
  (await RuleformRef.value).resetFields()
}
await getTemplateList();
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
/**
* 
* isTest  是否是测试群(0是  1否 )
* type   类型 (0企业微信  1钉钉)
* isUse  是否启用(0是  1否)
*/
const emit = defineEmits(['success','setClose']) // 定义 success 事件，用于操作成功后的回调
const setClose=()=>{
dialogVisible.value = false
emit('setClose')
}
const submitForm = async () => {
// 校验表单
if (!RuleformRef) return
const valid = await RuleformRef.value.validate()
if (!valid) return
// 提交请求
formLoading.value = true
try {
  const data = {...ruleForm.value};
   data.earthquakeType=data.earthquakeType.join(',')
   data.regionList=regionList.value;
  if (formType.value === 'create') {
    await ftpApi.savepictureRule(data)
    message.success(t('common.createSuccess'))
  } else {
    await ftpApi.savepictureRule(data)
    message.success(t('common.updateSuccess'))
  }
  dialogVisible.value = false
  // 发送操作成功的事件
  emit('success')
  setClose()
} finally {
  formLoading.value = false
}
}
const provinceRef = ref()
const regionList = ref([])
const voList = ref()
const regionLists = ref('')
const clickRadio = () => {
provinceRef.value.open();
console.log('allSchemas.formSchema',allSchemas.formSchema);

}

const clickClose = ()=>{
provinceRef.value?.close()
}
const querySelect=(value)=>{
ruleForm.value.regionList=value;
}
// 上传成功
const uploadSuccess = (value) => {
ruleForm.value.list = value;
}
const rangeRule0=ref([
{
  label: '震级',
  field: 'magnitude',
  colProps:{
      span:8
    }
},
{
  label: '扩展范围',
  field: 'extendedRange',
  colProps:{
      span:8
  }
},
{
  label: '间隔距离',
  field: 'intervalDistance',
  colProps:{
    span:8
  },
},
])
const rangeRule1=ref([
{
  label: '图层选择',
  field: 'layerType',
  isSearch: false,
  isTable:false,
  form:{
    component: 'Select',
    componentProps: {
        options: [
          {
            label: '影响场',
            value:1
          },
          {
            label: '历史地震',
            value:2
          },
          {
            label: '震中距',
            value:3
          }
      ]
    }
  },
},
{
  label: '扩展范围',
  field: 'extendedRange',
  isSearch: false,
  isTable:false,
},
])
const layerType1=[
{
  label: '烈度',
  field: 'intensityType',
  isSearch: false,
  isTable:false,
  form: {
    component: 'Select',
    componentProps: {
        options: intensityTypeOpt
    }
  }
},
{
  label: '未达烈度扩展范围',
  field: 'noExtendedRange',
  isSearch: false,
  isTable:false,
},
]
//添加图层选择项
const clickLayer= async (addformType)=>{
addformType.layerType=''
}
//添加图层选择项
const addLayerForm= async (addformType,type)=>{
if(type=='影响场'){
  addformType.forEach( async (item)=>{
  await addSchema(item)
})
}else{
  addformType.forEach( async (item)=>{
    await delRadioForm(item.field)
  })
}
}

//添加空间范围数据
const addRadioForm= async (addformType,deldata)=>{

addLayerForm(layerType1,'')
deldata.forEach( async (item)=>{
  await delRadioForm(item.field)
})
addformType.forEach( async (item)=>{
  await addSchema(item)
})
}
const delRadioForm= async (addformType)=>{
await delSchema(addformType)
}
//添加Form选项
const addSchema= async (data:any)=>{
const num =allSchemas.formSchema.length;

console.log('allSchemas.formSchema.findIndex(data)',num,);

if(allSchemas.formSchema.indexOf(data) == -1){
    RuleformRef.value.addSchema(data,num)
}
}
//删除Form选项
const delSchema= async (val)=>{
RuleformRef.value.delSchema(val)
}
const resultTypeOpt = ref([
{
  label:'公用',
  options:[]
},
{
  label:'专用',
  options:[]
}
]) // 弹窗的标题

const getTemplateList = async()=>{
const res= await ftpApi.pictureTemplateTwoList();
const opt=[
{
    label:'公用',
    options:res.publicList
  },
  {
    label:'专用',
    options:res.privateList
  }
]

resultTypeOpt.value=opt;
console.log('getTemplateList',res);

}
</script>

<style scoped>
.mapCard{
width: 400px;
height: 400px;
}
.el-colC{
text-align: center;
}
</style>